package cn.monkey.family.server.domain.sys.address;

import cn.monkey.family.data.Result;
import cn.monkey.family.data.context.Context;
import cn.monkey.family.data.context.RequestContext;
import cn.monkey.family.data.sys.address.AddressDto;
import cn.monkey.family.data.sys.address.AddressQueryRequest;
import cn.monkey.family.data.sys.address.AddressVo;
import com.google.common.base.Strings;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("address")
public class AddressController {

    private final IAddressService addressService;

    public AddressController(IAddressService addressService) {
        this.addressService = addressService;
    }

    @GetMapping({"{id}", ""})
    Result<?> get(@Context RequestContext context,
                  @PathVariable(value = "id", required = false) String id,
                  AddressQueryRequest queryRequest,
                  @RequestParam(value = "action", required = false) String action,
                  Pageable pageable) {
        if (!Strings.isNullOrEmpty(id)) {
            return this.addressService.readById(context, id);
        }
        if ("tree".equals(action)) {
            return this.addressService.readTree(context, queryRequest);
        }
        return this.addressService.readPage(context, queryRequest, pageable);
    }

    @PostMapping
    Result<AddressVo> create(@Context RequestContext context, @RequestBody AddressDto d) {
        return this.addressService.create(context, d);
    }

    @PutMapping("{id}")
    Result<AddressVo> update(@Context RequestContext context,
                             @PathVariable String id,
                             @RequestBody AddressDto d) {
        return this.addressService.update(context, id, d);
    }

    @DeleteMapping("{id}")
    Result<Void> delete(@Context RequestContext context,
                        @PathVariable String id) {
        return this.addressService.delete(context, id);
    }
}
